<template>
  <el-dialog :title="title" v-model="dialogVisible" width="70%" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%">
              <el-option
                v-for="project in projectOptions"
                :key="project.projectId"
                :label="project.projectName"
                :value="project.projectId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算周期" prop="periodType">
            <el-select v-model="form.periodType" placeholder="请选择结算周期" style="width: 100%">
              <el-option
                v-for="option in periodTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单" prop="orderId">
            <el-select v-model="form.orderId" placeholder="请选择订单" style="width: 100%">
              <el-option
                v-for="order in orderOptions"
                :key="order.orderId"
                :label="order.orderNo"
                :value="order.orderId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
              <el-option
                v-for="supplier in supplierOptions"
                :key="supplier.supplierId"
                :label="supplier.supplierName"
                :value="supplier.supplierId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择开始日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="选择结束日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div class="personnel-section" v-if="isFormValid">
      <div class="personnel-header">
        <h3>人员选择</h3>
        <el-button type="primary" size="small" @click="handleGenerateDetails">生成明细</el-button>
      </div>
      <el-checkbox v-model="selectAll" @change="handleSelectAllChange">全选</el-checkbox>
      <el-divider />
      <div class="personnel-list">
        <el-checkbox-group v-model="selectedPersonnelIds">
          <el-checkbox
            v-for="person in personnelList"
            :key="person.personnelId"
            :label="person.personnelId"
          >
            {{ person.personnelName }} ({{ person.personnelNo }})
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class="detail-section" v-if="form.details && form.details.length > 0">
      <h3>结算明细预览</h3>
      <el-table :data="form.details" border style="width: 100%; margin-top: 10px">
        <el-table-column prop="personnelId" label="人员ID" align="center" width="80" />
        <el-table-column prop="personnelName" label="人员姓名" align="center" min-width="120" />
        <el-table-column prop="attendanceDays" label="出勤天数" align="center" min-width="100" />
        <el-table-column prop="overtimeHours" label="加班时长(h)" align="center" min-width="120" />
        <el-table-column prop="monthlyRate" label="月薪(元)" align="center" min-width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.monthlyRate) }}
          </template>
        </el-table-column>
        <el-table-column prop="dailyRate" label="日薪(元)" align="center" min-width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.dailyRate) }}
          </template>
        </el-table-column>
        <el-table-column prop="overtimeRate" label="加班费率(元/h)" align="center" min-width="140">
          <template #default="scope">
            {{ formatAmount(scope.row.overtimeRate) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="金额(元)" align="center" min-width="120">
          <template #default="scope">
            <span class="amount">{{ formatAmount(scope.row.totalAmount) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="total-amount">
        <span>结算总金额: </span>
        <span class="amount">{{ formatAmount(totalAmount) }}</span>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, defineProps, defineEmits, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/add-circle-line";
import {
  addSettlement,
  updateSettlement,
  calculateSettlementDetails
} from "@/api/attendance/settlement";
import { SettlementVO, SettlementDetailVO, SettlementRequest } from "@/types/attendance/settlement";

// 定义属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  settlement: {
    type: Object as () => SettlementVO,
    default: () => ({
      id: undefined,
      projectId: undefined,
      orderId: undefined,
      supplierId: undefined,
      periodType: undefined,
      startDate: undefined,
      endDate: undefined,
      totalAmount: 0,
      remark: undefined,
      details: []
    }),
    required: true
  }
});

// 定义事件
const emit = defineEmits(["update:modelValue", "success"]);

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
});

// 表单引用
const formRef = ref<FormInstance>();

// 加载状态
const loading = ref(false);

// 项目选项
const projectOptions = ref([
  { projectId: 1, projectName: "项目A" },
  { projectId: 2, projectName: "项目B" },
  { projectId: 3, projectName: "项目C" }
]);

// 订单选项
const orderOptions = ref([
  { orderId: 1, orderNo: "DD-20240101-001" },
  { orderId: 2, orderNo: "DD-20240102-002" },
  { orderId: 3, orderNo: "DD-20240103-003" }
]);

// 供应商选项
const supplierOptions = ref([
  { supplierId: 1, supplierName: "供应商A" },
  { supplierId: 2, supplierName: "供应商B" },
  { supplierId: 3, supplierName: "供应商C" }
]);

// 结算周期类型选项
const periodTypeOptions = ref([
  { value: "MONTHLY", label: "按月结算" },
  { value: "QUARTERLY", label: "按季度结算" },
  { value: "HALF_YEARLY", label: "按半年结算" }
]);

// 表单数据
const form = reactive<SettlementVO>({
  id: undefined,
  projectId: undefined,
  orderId: undefined,
  supplierId: undefined,
  periodType: undefined,
  startDate: undefined,
  endDate: undefined,
  totalAmount: 0,
  remark: undefined,
  details: []
});

// 初始化表单数据
const initFormData = () => {
  if (props.settlement) {
    form.id = props.settlement.id;
    form.projectId = props.settlement.projectId;
    form.orderId = props.settlement.orderId;
    form.supplierId = props.settlement.supplierId;
    form.periodType = props.settlement.periodType;
    form.startDate = props.settlement.startDate;
    form.endDate = props.settlement.endDate;
    form.totalAmount = props.settlement.totalAmount || 0;
    form.remark = props.settlement.remark;
    form.details = props.settlement.details || [];
  }
};

// 监听props.settlement变化，更新表单数据
watch(
  () => props.settlement,
  newVal => {
    if (newVal) {
      initFormData();
    }
  },
  { deep: true, immediate: true }
);

// 人员列表
const personnelList = ref([
  { personnelId: 1, personnelName: "张三", personnelNo: "P001" },
  { personnelId: 2, personnelName: "李四", personnelNo: "P002" },
  { personnelId: 3, personnelName: "王五", personnelNo: "P003" },
  { personnelId: 4, personnelName: "赵六", personnelNo: "P004" }
]);

// 是否全选
const selectAll = ref(false);

// 选中的人员ID列表
const selectedPersonnelIds = ref<number[]>([]);

// 表单校验规则
const rules = {
  projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
  orderId: [{ required: true, message: "请选择订单", trigger: "change" }],
  supplierId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  periodType: [{ required: true, message: "请选择结算周期", trigger: "change" }],
  startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结束日期", trigger: "change" }]
};

// 表单是否有效
const isFormValid = computed(() => {
  return (
    !!form.projectId &&
    !!form.orderId &&
    !!form.supplierId &&
    !!form.periodType &&
    !!form.startDate &&
    !!form.endDate
  );
});

// 结算总金额
const totalAmount = computed(() => {
  if (!form.details || form.details.length === 0) {
    return 0;
  }
  return form.details.reduce((sum, detail) => sum + (detail.totalAmount || 0), 0);
});

// 监听全选变化
const handleSelectAllChange = (val: boolean) => {
  if (val) {
    selectedPersonnelIds.value = personnelList.value.map(item => item.personnelId);
  } else {
    selectedPersonnelIds.value = [];
  }
};

// 监听选中的人员ID变化
watch(
  selectedPersonnelIds,
  newVal => {
    selectAll.value = newVal.length === personnelList.value.length;
  },
  { deep: true }
);

// 生成明细
const handleGenerateDetails = async () => {
  if (selectedPersonnelIds.value.length === 0) {
    ElMessage.warning("请至少选择一名人员");
    return;
  }

  try {
    const res = await calculateSettlementDetails({
      orderId: form.orderId!,
      startDate: form.startDate!,
      endDate: form.endDate!,
      personnelIds: selectedPersonnelIds.value
    });

    form.details = res.data;
    form.totalAmount = totalAmount.value;
  } catch (error) {
    console.error("生成明细失败", error);
  }
};

// 格式化金额
const formatAmount = (amount: number | undefined) => {
  if (amount === undefined || amount === null) {
    return "¥0.00";
  }
  return amount.toLocaleString("zh-CN", {
    style: "currency",
    currency: "CNY",
    minimumFractionDigits: 2
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      if (!form.details || form.details.length === 0) {
        ElMessage.warning("请先生成结算明细");
        return;
      }

      try {
        const data = {
          id: form.id,
          projectId: form.projectId!,
          orderId: form.orderId!,
          supplierId: form.supplierId!,
          periodType: form.periodType,
          startDate: form.startDate!,
          endDate: form.endDate!,
          totalAmount: totalAmount.value,
          remark: form.remark,
          personnelIds: selectedPersonnelIds.value
        };

        if (form.id) {
          // 修改
          await updateSettlement(data);
          ElMessage.success("修改成功");
        } else {
          // 新增
          await addSettlement(data);
          ElMessage.success("新增成功");
        }

        dialogVisible.value = false;
        emit("success");
      } catch (error) {
        console.error("提交失败", error);
      }
    }
  });
};

// 页面加载时获取相关数据
onMounted(() => {
  // 初始化表单数据
  initFormData();

  // TODO: 从接口获取项目、订单、供应商、人员列表数据
  // 示例: 获取订单关联的人员
  if (form.orderId) {
    // TODO: 根据orderId获取人员列表
  }
});
</script>

<style lang="scss" scoped>
.personnel-section,
.detail-section {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #f8f8f8;

  h3 {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
  }
}

.personnel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.personnel-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.total-amount {
  margin-top: 15px;
  text-align: right;
  font-size: 16px;

  .amount {
    color: #f56c6c;
    font-weight: bold;
    font-size: 18px;
    margin-left: 5px;
  }
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}
</style>
